<template>
  <div class="page-content">
    <div class="title-detail text-center font-size-18 text-bold">
      {{userInfo.company_name}}—{{selTree.plant.label}}{{selTree.line.id === null ? '' : `—${selTree.line.label}`}}
    </div>
    <div class="title flex justify-between items-center" style="margin-top: -34px;margin-bottom: 10px">
      <div>
        当前班制：{{shifts.name}}
        <span v-if="shifts.name.length>0" class="small-title">({{shifts.startTime}}—{{shifts.endTime}})</span>
        <span>{{workFlagName}}</span>
      </div>
      <div class="text-right">
        <q-toggle v-model="showScale"
                  label="启用缩放"
                  left-label
                  @input="changeScale"
                  size="16px"
        />
        <q-btn @click="showSelPlantDialog" class="more-btn" round flat dense size="sm" color="primary" icon="iconfont icontubiao-74" />
      </div>
    </div>
    <div class="flex justify-end margin-b-20"><Legend /></div>
    <div class="flex-1 content-container scroll-y scrollbar">
      <div class="flex" style="align-items:stretch;width: calc(100% + 8px)">
        <div class="right-container">
          <div class="row">
            <div class="col-lg-6 col-xs-12 item margin-b-20">
              <box title="当日实时状态分布" class="content" tips="所选车间内安装语祯盒子的机床在当前时刻各状态的台数占比" @big="showPieDialog(realTimeStatus, realTimeTotal, '实时状态分布', 'percent')">
                <template v-slot:content>
                  <pie :info="realTimeStatus" :total="realTimeTotal"></pie>
                </template>
              </box>
            </div>
            <div class="col-lg-6 col-xs-12 item margin-b-20">
              <box title="当班状态统计" class="content" tips="所选车间内安装语祯盒子的机床在当前轮班内各状态的时长占比，报警和故障可以和其他状态同时出现" @big="showPieDialog(curStatus, curTotal, '当班状态统计', 'time')">
                <template v-slot:content>
                  <CurStatus :info="curStatus" :total="curTotal" type="time"></CurStatus>
                </template>
              </box>
            </div>
            <div class="col-12 margin-b-20 item">
              <box title="当班停机原因" @big="showBarDialog" style="position:relative">
                <template v-slot:content>
                  <div class="not-fill-detail" @click="goNotFillDetail" :class="{'disable-detail': !notWriteShow}">未填写详情 ></div>
                  <div class="barChart chart-container" ref="barChart"></div>
                </template>
              </box>
            </div>
            <div class="col-12 item">
              <box title="当班不良统计" @big="showLineDialog">
                <template v-slot:content>
                  <div class="lineChart chart-container" ref="lineChart"></div>
                </template>
              </box>
            </div>
          </div>
        </div>
        <div class="left-container column">
            <div class="margin-b-20">
              <box title="实时作业状态分布" class="content" :isShowBig="false">
                <template v-slot:content>
                  <realtime-job :info="realtimeJobData" type="time"></realtime-job>
                </template>
              </box>
            </div>
          <div class="full-width" style="padding-bottom: 10px;max-height: 50%">
            <div class="list-container page-content">
              <div class="font-size-16 margin-b-20" style="cursor: pointer" @click="dialogVisible=true">
                <span style="margin-right: 6px">当班设备时间开动率排行</span>
                <span>
                  <q-icon name="iconfont icontubiao-72" class="font-18 text-grey" />
                  <q-tooltip max-width="300px">当班设备时间开动率 = 设备实际加工时长/计划工作时长</q-tooltip>
                </span>
              </div>
                <q-table
                  :data="rankTableData" :columns="rankColumns"
                  row-key="id" class="scroll myTable-line rank-table full-width no-last-bor"
                  style="max-height: 456px"
                  hide-bottom :pagination="{rowsPerPage: 0}"
                  no-data-label="暂无数据">
                  <template v-slot:body="props">
                    <q-tr :props="props">
                      <q-td key="rank" :props="props">
                        <div v-if="props.row.index > 3" class="text-center rank-index">{{ props.row.index }}</div>
                        <img v-else :src="'statics/img/'+props.row.index+'.png'" class="img-h" alt="">
                      </q-td>
                      <q-td key="device" :props="props">{{ props.row.deviceName + `(${props.row.assetNumber})` }}</q-td>
                      <q-td key="percent" :props="props">{{ props.row.operatingRate }}</q-td>
                    </q-tr>
                  </template>
                </q-table>
            </div>
          </div>
          <div class="full-width" style="padding-top: 10px;max-height: 50%">
            <div class="list-container page-content">
              <div class="font-size-16 margin-b-20">
                <span>事件列表</span>
              </div>
              <q-table
                :data="tableData" :columns="columns"
                row-key="id" class="scroll myTable-line full-width no-last-bor"
                style="max-height: 456px"
                :loading="tableLoading"
                hide-bottom :pagination="{rowsPerPage: 0}"
                no-data-label="暂无数据">
                <template v-slot:body="props">
                  <q-tr :props="props">
                    <q-td key="type" :props="props">
                      <span class="round" :style="{'background-color':eventColor[props.row.type]}"></span>
                      {{ props.row.statusText }}
                    </q-td>
                    <q-td key="device" :props="props">{{ props.row.deviceName }}({{props.row.assetNumber}})</q-td>
                    <q-td key="time" :props="props">{{ props.row.time }}</q-td>
                  </q-tr>
                </template>
              </q-table>
            </div>
          </div>
        </div>
      </div>
    </div>
    <sel-plant-dialog ref="selPlantDialog" :treeList="treeList" @submit="changeSel" />
    <pie-dialog ref="pieDialog" :chart-color="eventColor" :explain="eventExplain" />
    <cur-status-dialog ref="curStatusDialog" />
    <line-dialog ref="lineDialog" />
    <bar-dialog ref="barDialog" />
    <drawer
      title="说明"
      :visible.sync="dialogVisible"
      width="500px"
      close-on-click-modal>
      <div>
        <div>1.设备开动率按照公式（当班设备开动率 = 设备实际加工状态总时长 / 当班内计划工作总时长）</div>
        <div>2.设备未产生加工状态时长时，统一显示0.00%</div>
      </div>
    </drawer>
  </div>
</template>

<script>
import Box from './components/box'
import Pie from './components/pie'
import CurStatus from './components/cur-status'
import realtimeJob from './components/realtime-job'
import CurStatusDialog from './components/cur-status-dialog'
import SelPlantDialog from './components/sel-plant-dialog'
import PieDialog from './components/pie-dialog'
import LineDialog from './components/line-dialog'
import BarDialog from './components/bar-dialog'
import echarts from 'echarts'
import { mapGetters, mapActions } from 'vuex'
import { getOrganizeNested } from 'src/boot/factory/organize'
import Legend from './components/legend'
// import { getRealtimeStatus, getCurStatus, getStopReason,
import {
  getRealtimeStatus, getStopReason, getCurStatus,
  getBadChart, getShifts, getDeviceRate, getMessage, getStatisticsState, getStopNotWrite
} from 'src/boot/home/home'
import refreshMixin from '../../assets/js/refresh-mixin'
import { date } from 'quasar'
import _ from 'lodash'
import { addListener } from 'resize-detector'
import Drawer from 'src/components/drawer/drawer'
import moment from 'moment'
export default {
  name: 'stats-statistics',
  mixins: [refreshMixin],
  data () {
    return {
      dialogVisible: false,
      showScale: false, // 是否可以缩放
      pageName: 'home', // 页面name
      treeList: [], // 分厂车间树形数据
      selTree: {
        factory: {},
        plant: {},
        line: {
          id: null
        }
      },
      oldPlantId: null,
      isFindPlant: false,
      shifts: {
        name: '',
        id: '',
        startTime: '',
        endTime: '',
        workFlag: 0
      },
      workFlagName: '',
      // 实时状态
      realTimeStatus: {
        process: 0, // 加工
        stop: 0, // 停机
        breaks: 0, // 断开
        offLine: 0, // 离线
        alert: 0, // 报警
        changeLine: 0, // 换线
        fault: 0, // 故障
        repair: 0 // 维修
      },
      // 实时数量
      realTimeTotal: 0,
      // 缓存实时状态数据
      realTimeStatusData: [],
      // 当班状态
      curStatus: {
        process: 0, // 加工
        stop: 0, // 停机
        breaks: 0, // 断开
        offLine: 0, // 离线
        alarm: 0, // 报警
        changeLine: 0, // 换线
        fault: 0, // 故障
        repair: 0 // 维修
      },
      // 实时作业状态分布
      realtimeJobData: {
        normalDeviceCount: 0, // 正常
        slightSlowDeviceCount: 0, // 轻微落后
        severeDeviceCount: 0, // 严重落后
        idleDeviceCount: 0 // 暂未派工
      },
      // 当班数量
      curTotal: 0,
      barChart: null, // 当班停机原因柱状图
      barData: [],
      // 当班不良统计
      lineChart: null, // 当班不良统计柱状图
      lineData: [],
      // 事件列表
      tableLoading: false, // table加载时使用
      tableData: [], // table数据
      columns: [ // 事件标题
        { name: 'type', align: 'left', label: '状态类型', field: 'type', check: true, style: 'width: 120px' },
        { name: 'device', align: 'left', label: '设备', field: 'device', check: true },
        { name: 'time', align: 'left', label: '发生时间', field: 'time', check: true, style: 'width: 158px' }
      ],
      // 开动率排行榜列表
      rankTableLoading: false, // table加载时使用
      rankTableData: [], // table数据
      rankColumns: [ // 事件标题
        { name: 'rank', align: 'left', label: '当前排名', field: 'rank', check: true },
        { name: 'device', align: 'left', label: '设备', field: 'device', check: true },
        { name: 'percent', align: 'left', label: '设备开动率', field: 'percent', check: true, style: 'width: 80px' }
      ],
      // 事件对应颜色
      eventColor: {
        process: '#18D77F', // 加工
        stop: '#FF8559', // 停机
        breaks: '#999999', // 断开
        offLine: '#666666', // 离线
        alert: '#E43434', // 报警
        changeLine: '#AC70F2', // 换线
        fault: '#F7B82D', // 故障
        repair: '#2bd0f7' // 维修
      },
      // 事件名称列表
      eventExplain: {
        process: '加工',
        stop: '停机',
        breaks: '断开',
        offLine: '离线',
        alert: '报警',
        changeLine: '换线',
        fault: '故障',
        repair: '维修'
      },
      // 值对应事件名称
      eventValue: {
        0: 'stop',
        1: 'process',
        2: 'offLine',
        3: 'breaks',
        4: 'alert',
        5: 'changeLine',
        6: 'fault',
        7: 'repair',
        51: 'process'
      },
      timer: null,
      stopRequest: false,
      stopNotWrite: []
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'permissions', 'client']),
    notWriteShow () {
      return this.shifts.name.length > 0 && this.stopNotWrite.length > 0
    }
  },
  watch: {
    permissions () {
      let self = this
      this.getSelData()
      window.onresize = () => {
        return (() => {
          self.barChart.resize()
          self.lineChart.resize()
        })()
      }
    }
  },
  created () {
    this.getSelData()
  },
  mounted () {
    addListener(this.$refs.barChart, this.$utils.debounce(() => {
      if (this.barChart) {
        this.barChart.resize()
      }
      if (this.lineChart) {
        this.lineChart.resize()
      }
    }, 100))

    // this._listenAlt()
    // 判断有没有机台状态模块
    let self = this
    window.onresize = () => {
      return (() => {
        self.barChart.resize()
        self.lineChart.resize()
      })()
    }
  },
  destroyed () {
    clearTimeout(this.timer)
    this.timer = null
    if (this.oldPlantId) {
      this.client.unsubscribe(this.oldPlantId)
    }
  },
  methods: {
    ...mapActions([
      'getWebScoket'
    ]),
    // 图表缩放
    changeScale () {
      let optionBarChart = _.cloneDeep(this.barChart.getOption())
      optionBarChart.dataZoom[0].disabled = !this.showScale
      this.barChart.clear()
      this.barChart.setOption(optionBarChart)
      let optionLineChart = _.cloneDeep(this.lineChart.getOption())
      optionLineChart.dataZoom[0].disabled = !this.showScale
      this.lineChart.clear()
      this.lineChart.setOption(optionLineChart)
    },
    // 刷新
    refreshInfo () {
      clearTimeout(this.timer)
      this.timer = null
      this.getSelData()
    },
    getStopNotWriteInfo () {
      let today = moment().format('YYYY-MM-DD')
      if (moment().diff(moment(today + 'T' + this.shifts.startTime)) < 0) {
        today = moment().add(-1, 'days')
      }
      const startDate = moment(today).format('YYYY-MM-DDT') + this.shifts.startTime
      const endDate = this.shifts.isEndTimeOnNextDay ? moment(today).add(1, 'days').format('YYYY-MM-DDT') + this.shifts.endTime : moment(today).format('YYYY-MM-DDT') + this.shifts.endTime
      const params = {
        schemeId: (this.selTree.line && this.selTree.line.id) ? this.selTree.line.id : this.selTree.plant.id,
        schemeLevel: (this.selTree.line && this.selTree.line.id) ? '3' : '2',
        since: startDate,
        end: endDate
      }
      this.stopNotWrite = []
      getStopNotWrite(params).then(res => {
        this.stopNotWrite = res.data
      })
    },
    // 订阅消息
    onSubscribe () {
      if (this.client) {
        if (this.oldPlantId) {
          this.client.unsubscribe(this.oldPlantId)
        }
        this.client.subscribe(`${this.CommonConfig.socketConfig.SOCKET_TOPIC.realTimeStatus.subscribeTopic}${this.selTree.plant.id}`, this.onMessageArrived, { id: this.selTree.plant.id })
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    /**
     * 接受盒子返回消息
     * @param {string} message
     */
    onMessageArrived (message) {
      let data = JSON.parse(message.body).data
      console.log(data.deviceId, 'miao')
      // 状态码优先级定义
      let priority = {
        '1': [0, 1, 2, 3],
        '2': [4],
        '3': [5],
        '4': [6, 7]
      }
      // 实时状态分布
      if (this.realTimeStatusData[data.deviceId]) {
        let statusArr = JSON.parse(JSON.stringify(this.realTimeStatusData[data.deviceId]))
        // console.log(this.realTimeStatusData[data.boxId])
        switch (data.statusCode) {
          // 判断是否是报警相关
          case 4:
            // 报警时，数据变成[6,5,4,1],[5,4,1],[4,1],[5,4,2],[4,2],[5,4,3],[4,3]
            if (data.statusText === '报警') {
              // 长度为1时，把4塞进去就好了，变成[4,1]
              if (statusArr.length === 1) {
                statusArr.unshift(data.statusCode)
              } else {
                // 长度不为1
                // 如果不存在4(数据是[6,5,1],[5,1],[6,1])，就在倒数第二位插入4（数据变成[6,5,4,1][5,4,1],[6,4,1]）
                // 如果存在4，就保持原状
                if (statusArr.indexOf(4) === -1) {
                  // 在倒数第二位插入4
                  statusArr.splice(-1, 0, data.statusCode)
                }
              }
            } else if (data.statusText === '报警解除') {
              // 报警解除时，去掉4
              statusArr = statusArr.filter(item => {
                return item !== 4
              })
            }
            break
          // 换线
          case 5:
            // 换线时，数据变成[6,5,4,1],[5,4,1], [5,1], [5,4,2], [5,2], [5,4,3], [5,3]
            if (statusArr.length === 1) {
              // 长度为1时，把5塞进去就好了，变成[5,1]
              statusArr.unshift(data.statusCode)
            } else {
              // 长度不为1时
              // 如果不存在5（数据是[4,1],[6,1]），就把5插入进去（数据变成[5,4,1],[6,5,1]）
              // 如果存在5（数据是[5,1]）,就保持原状
              if (statusArr.indexOf(5) === -1) {
                // 判断数组里存在高级别的6,7,就在第二位添加5
                if (statusArr.indexOf(priority['4'][0]) > -1 || statusArr.indexOf(priority['4'][1]) > -1) {
                  statusArr.splice(1, 0, data.statusCode)
                } else {
                  // 否则在第一位插入5
                  statusArr.splice(0, 0, data.statusCode)
                }
              }
            }
            break
          // 换线结束，去掉5
          case 51:
            if (data.statusCode === 51) {
              statusArr = statusArr.filter(item => {
                return item !== 5
              })
            }
            break
          // 故障、维修
          case 6:
          case 7:
            if (data.overFlag) {
              // 状态解除，去掉对应的错误码
              statusArr = statusArr.filter(item => {
                return item !== data.statusCode
              })
            } else {
              // 状态添加
              // 故障时，数据变成[6,5,4,1],[6,4,1],[6,1]
              // 维修时，数据变成[7,5,4,1],[7,4,1],[7,1]
              if (statusArr.length === 1) {
                // 长度为1时，把状态塞进去就好了，变成[6,1]或者[7,1]
                statusArr.unshift(data.statusCode)
              } else {
                // 长度不为1
                // 判断第一位是否是6或者7
                if (priority['4'].indexOf(statusArr[0]) > -1) {
                  // 第一位是最高级别，就替换
                  statusArr.splice(0, 1, data.statusCode)
                } else {
                  // 第一位不是最高级别数据，就插入到第一位
                  statusArr.splice(0, 0, data.statusCode)
                }
              }
            }
            break
          // 其他状态修改最后一位
          default:
            statusArr.splice(statusArr.length - 1, 1, data.statusCode)
            break
        }
        this.realTimeStatusData[data.deviceId] = statusArr
        // console.log(this.realTimeStatusData[data.boxId])
        this.realTimeStatus = this.initRealTimeStatus(this.realTimeStatusData)

        // 消息列表
        if (data.statusCode === 4 || data.statusCode === 6 || data.statusCode === 7) {
          let hasMessageIndex = this.tableData.findIndex(item => {
            return date.formatDate(item.time, 'YYYY-MM-DD HH:mm:ss') === date.formatDate(data.time, 'YYYY-MM-DD HH:mm:ss') &&
              item.deviceId === data.deviceId && item.type === this.eventValue[Number(data.statusCode)]
          })
          if (hasMessageIndex === -1) {
            let message = {
              ...data,
              type: this.eventValue[Number(data.statusCode)],
              time: date.formatDate(data.time, 'YYYY-MM-DD HH:mm:ss')
            }
            if (data.statusCode === 4) {
              message.eventDesc = data.alarmContent
            }
            this.tableData.unshift(message)
            // 只保留前20条
            this.tableData = this.tableData.length > 20 ? this.tableData.slice(0, 21) : this.tableData
          }
        }
      }
    },
    getSelData () {
      getOrganizeNested().then(res => {
        this.treeList = res.data
        if (res.data.length > 0) {
          this.setSelTree()
          this.onSubscribe()
          this.getShifts()
        }
      })
    },
    // 获取班制
    getShifts () {
      if (this.timer === null) {
        clearTimeout(this.timer)
        this.timer = null
      }
      getShifts(this.selTree.plant.id).then(res => {
        if (res.data) {
          this.shifts.name = res.data.name || ''
          this.shifts.id = res.data.id || ''
          this.workFlag = res.data.workFlag || 0
          let workFlagName
          switch (this.workFlag) {
            case 0:
              workFlagName = '休息中'
              break
            case 1:
              workFlagName = '工作中'
              break
            case 2:
              workFlagName = '换班中'
              break
            case 3:
              workFlagName = '休息日'
              break
            case 4:
              workFlagName = '未排班'
              break
            default:
              workFlagName = '--'
              break
          }
          this.workFlagName = workFlagName
          // this.shifts.startTime = this.getCalculateTime(res.data.startTime, res.data.isStartTimeOnNextDay)
          // this.shifts.endTime = this.getCalculateTime(res.data.endTime, res.data.isEndTimeOnNextDay)
          this.shifts.startTime = res.data.startTime ? this.getTime(res.data.startTime) : ''
          this.shifts.endTime = res.data.endTime ? this.getTime(res.data.endTime) : ''
          this.shifts.isStartTimeOnNextDay = res.data.isStartTimeOnNextDay
          this.shifts.isEndTimeOnNextDay = res.data.isEndTimeOnNextDay
          this.shifts.isYesterday = res.data.isYesterday
          this.$q.loading.show()
          // 无班制时依然显示 任务I2B03R
          if (res.data.startTime && res.data.endTime) {
            // 有班制时间请求当班数据
            this.getData()
            this.getStopNotWriteInfo()
          } else {
            // this.errMessage('当前时间没有启用的班制')
            this.removeData()
            clearTimeout(this.timer)
            this.timer = null
          }
          // 实时不受班制时间限制
          this.getRealData()
          this.refreshData()
        } else {
          // this.errMessage('当前时间没有启用的班制')
          this.removeData()
          clearTimeout(this.timer)
          this.timer = null
        }
      }).catch(() => {
        this.removeData()
        clearTimeout(this.timer)
        this.timer = null
      })
    },
    // 判断是否跨天后的时间
    getCalculateTime (time, onNext) {
      console.log(moment(time).format('YYYY-MM-DDTHH:mm:ss'))
      // return onNext ? moment("time")
    },
    // 失败提示
    errMessage (message) {
      this.$message.error(message)
    },
    getTime (time) {
      let timeArr = time.split(':')
      return timeArr[0] + ':' + timeArr[1]
    },
    // 获取实时数据
    getRealData () {
      // let params2 = this.getDateTime(this.shifts)
      const params = {}
      this.selTree.line.id !== null && (params['lineId'] = this.selTree.line.id)
      // 实时状态分布
      getRealtimeStatus(params, this.selTree.plant.id).then(res => {
        this.realTimeStatusData = res.data
        this.realTimeStatus = this.initRealTimeStatus(res.data)
        this.realTimeTotal = res.data.length
      })
    },
    // 获取当班实时的数据
    getData () {
      Object.assign(this.realtimeJobData, this.$options.data.call(this).realtimeJobData)
      // this.$q.loading.show()
      let params2 = this.getDateTime(this.shifts)

      this.selTree.line.id !== null && (params2['lineId'] = this.selTree.line.id)
      let params1 = {
        ...params2,
        workshopId: this.selTree.plant.id
      }
      // 当班状态分布
      getCurStatus(params1).then(res => {
        // this.curTotal = this.getTotal(res.data)
        this.curTotal = res.data.total
        this.curStatus = res.data
        delete this.curStatus.total
      })
      // 获取实时作业状态分布
      getStatisticsState(params1).then(res => {
        this.realtimeJobData = Object.assign({}, this.realtimeJobData, res.data)
      }).catch(err => {
        console.log(err)
      })
      // 获取当班停机原因
      getStopReason(params2, this.selTree.plant.id).then(res => {
        this.barData = this.initStopReason(res.data)
        this.setBarOption()
      })
      // 获取当班不良统计
      getBadChart(params2, this.selTree.plant.id, this.shifts.id).then(res => {
        this.lineData = res.data
        this.setLineOption()
      })
      let params3 = {
        ...params2,
        shiftId: this.shifts.id
      }
      // 获取当班设备开动率
      getDeviceRate(params3, this.selTree.plant.id, this.shifts.id).then(res => {
        this.rankTableData = this.initRankTableData(res.data)
      })
      let params4 = {
        ...params2,
        workshopId: this.selTree.plant.id,
        pageSize: 20
      }
      // 消息列表
      getMessage(params4).then(res => {
        this.tableData = this.initAlertTableData(res.data)
      })

      this.$q.loading.hide()
    },
    // 重构实时状态分布
    initRealTimeStatus (info) {
      let realTimeStatus = {
        process: 0, // 加工
        stop: 0, // 停机
        breaks: 0, // 断开
        offLine: 0, // 离线
        alert: 0, // 报警
        changeLine: 0, // 换线
        fault: 0, // 故障
        repair: 0 // 维修
      }
      for (let key in info) {
        switch (info[key][0]) {
          case 0:
            ++realTimeStatus.stop
            break
          case 1:
          case 51:
            ++realTimeStatus.process
            break
          case 2:
            ++realTimeStatus.offLine
            break
          case 3:
            ++realTimeStatus.breaks
            break
          case 4:
            ++realTimeStatus.alert
            break
          case 5:
            ++realTimeStatus.changeLine
            break
          case 6:
            ++realTimeStatus.fault
            break
          case 7:
            ++realTimeStatus.repair
            break
        }
      }
      return realTimeStatus
    },
    // 重构设备开动率数据
    initRankTableData (data) {
      return data.map((item, index) => {
        return {
          ...item,
          index: index + 1,
          operatingRate: (item.operatingRate * 100).toFixed(2) + '%'
        }
      })
    },
    // 重构消息数据
    initAlertTableData (data) {
      return data.map(item => {
        return {
          ...item,
          type: this.eventValue[Number(item.statusCode)],
          time: date.formatDate(item.time, 'YYYY-MM-DD HH:mm:ss')
        }
      })
    },
    // 重构停机原因
    initStopReason (data) {
      return data.map(item => {
        return {
          ...item,
          value: (item.value / 60).toFixed(2)
        }
      })
    },
    // 刷新数据
    refreshData () {
      if (this.$route.name !== 'home') {
        clearTimeout(this.timer)
        this.timer = null
        return
      }

      this.timer = setTimeout(this.getShifts, 300000)
    },
    // 让数据为空
    removeData () {
      // 班制
      this.shifts = {
        name: '',
        id: '',
        startTime: '',
        endTime: '',
        workFlag: 0
      }
      // 实时状态
      this.realTimeStatus = {
        process: 0, // 加工
        stop: 0, // 停机
        breaks: 0, // 断开
        offLine: 0, // 离线
        alert: 0, // 报警
        changeLine: 0, // 换线
        fault: 0, // 故障
        repair: 0 // 维修
      }
      this.realTimeStatusData = {}
      // 重置数据
      Object.assign(this.realtimeJobData, this.$options.data.call(this).realtimeJobData)
      // 实时数量
      this.realTimeTotal = 0
      // 当班状态
      this.curStatus = {
        process: 0, // 加工
        stop: 0, // 停机
        breaks: 0, // 断开
        offLine: 0, // 离线
        alarm: 0, // 报警
        changeLine: 0, // 换线
        fault: 0, // 故障
        repair: 0 // 维修
      }
      // 当班数量
      this.curTotal = 0
      this.barData = []
      this.lineData = []
      // this.barData.forEach(item => {
      //   item.value = 0
      // })
      // this.lineData.forEach(item => {
      //   item.value = 0
      // })
      // 报警列表
      this.tableData = []
      this.rankTableData = []
      // 设备开动率
      this.rankTableData = []
      this.setBarOption()
      this.setLineOption()
      this.$q.loading.hide()
    },
    // 获取一共的数量
    getTotal (info) {
      let total = 0
      for (let key in info) {
        total += info[key]
      }
      return total
    },
    setSelTree () {
      for (let i = 0; i < this.treeList.length; i++) {
        if (this.treeList[i].label !== 'default') {
          this.selTree.plant = this.treeList[i]
          this.isFindPlant = true
          break
        }
        if (this.isFindPlant) {
          break
        }
      }
      // 无车间提示
      if (!this.isFindPlant) {
        this.$message.warning('请先在“基础数据-工厂建模”里创建的分厂下面创建车间！')
      }
    },
    // 选择车间
    changeSel (selTree) {
      if (selTree.plant.hash !== this.selTree.plant.hash || selTree.line.id !== this.selTree.line.id) {
        this.oldPlantId = this.selTree.plant.id
        this.selTree = JSON.parse(JSON.stringify(selTree))
        this.getShifts()
        this.onSubscribe()
      }
    },
    // 显示柱状图
    setBarOption () {
      const xData = this.barData.map(item => {
        if (item.name.length > (11 - this.barData.length)) {
          let newName = item.name.slice(0, 12 - this.barData.length)
          newName += '...'
          return newName
        }
        return item.name
      })
      let max = this.getMax(this.barData)
      let option = {
        grid: {
          top: 35,
          bottom: 30,
          left: String(max).length < 4 ? 40 : 60,
          right: 0
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true
            }
          },
          formatter: (params, ticket, callback) => {
            let htmlStr = ''
            let value = params[0].value
            let color = `linear-gradient(#44D8C6, #5F77FD)`
            let name = params[0].name

            htmlStr += '<div>' + name + '</div>'
            htmlStr += '<div>'
            htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-image:' + color + ';"></span>'
            htmlStr += value + '分钟'

            htmlStr += '</div>'
            return htmlStr
          }
        },
        dataZoom: [
          {
            type: 'inside',
            disabled: !this.showScale,
            xAxisIndex: 0
          }
        ],
        xAxis: {
          type: 'category',
          data: xData,
          axisTick: {
            show: false // 隐藏X轴刻度
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#333333', // X轴文字颜色
              fontSize: 14
            },
            interval: 0
          },
          axisLine: {
            show: true, // 隐藏X轴轴线
            lineStyle: {
              color: '#d3d3d3'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '时间(min)',
          nameTextStyle: {
            color: '#333333',
            fontSize: 14
          },
          nameGap: 20,
          // interval: 30,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#DDD'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#333333',
              fontSize: 14
            }
          },
          axisLine: {
            show: false
          }
        },
        series: {
          type: 'bar',
          barWidth: 16,
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: '#44D8C6'
              },
              {
                offset: 1,
                color: '#5F77FD'
              }]),
              barBorderRadius: [6, 6, 0, 0]
            }
          },
          label: {
            show: true,
            position: 'top',
            color: '#5F77FD',
            fontSize: 12
          },
          data: this.barData
        }
      }
      if (this.barChart === null) {
        this.barChart = echarts.init(this.$refs.barChart)
      }
      this.barChart.setOption(option)
    },
    // 显示折线图
    setLineOption () {
      const xData = this.lineData.map(item => {
        if (item.name.length > (11 - this.lineData.length)) {
          let newName = item.name.slice(0, 12 - this.lineData.length)
          newName += '...'
          return newName
        }
        return item.name
      })
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              type: 'dashed'
            }
          },
          formatter: function (params, ticket, callback) {
            let htmlStr = ''
            let value = params[0].value
            let color = params[0].color

            htmlStr += '<div>'
            htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + color + ';"></span>'
            htmlStr += value + '个'

            htmlStr += '</div>'
            return htmlStr
          }
        },
        dataZoom: [
          {
            type: 'inside',
            disabled: !this.showScale,
            xAxisIndex: 0
          }
        ],
        grid: {
          top: 35,
          bottom: 30,
          left: 40,
          right: 0
        },
        xAxis: [{
          type: 'category',
          data: xData,
          axisTick: {
            show: false // 隐藏X轴刻度
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#333333', // X轴文字颜色
              fontSize: 14
            },
            interval: 0
          },
          axisLine: {
            show: true, // 隐藏X轴轴线
            lineStyle: {
              color: '#d3d3d3'
            }
          }
        }],
        yAxis: [{
          type: 'value',
          name: '数量',
          nameTextStyle: {
            color: '#333333',
            fontSize: 14
          },
          nameGap: 20,
          // interval: 30,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#DDD'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#333333',
              fontSize: 14
            }
          },
          axisLine: {
            show: false
          }
        }],
        series: [{
          name: '开动率',
          type: 'line',
          data: this.lineData,
          lineStyle: {
            normal: {
              width: 5,
              color: '#5F77FD',
              shadowColor: 'rgba(95, 119, 253, 0.3)',
              shadowBlur: 10,
              shadowOffsetY: 20
            }
          },
          symbolSize: 15,
          itemStyle: {
            normal: {
              color: '#5F77FD',
              borderWidth: 3,
              borderColor: '#5F77FD'
            },
            emphasis: {
              color: '#5F77FD',
              borderColor: '#5F77FD'
            }
          },
          smooth: true
        }]
      }
      if (this.lineChart === null) {
        this.lineChart = echarts.init(this.$refs.lineChart)
      }
      this.lineChart.setOption(option)
    },
    // 显示选择车间的弹框
    showSelPlantDialog () {
      if (!this.isFindPlant) {
        this.$message.warning('请先在“基础数据-工厂建模”里创建的分厂下面创建车间！')
        return
      }
      this.$refs.selPlantDialog.showDialog(this.selTree)
    },
    // 放大Pie
    showPieDialog (info, total, title, type) {
      if (type === 'time') {
        this.$refs.curStatusDialog.showDialog(info, total, title)
      } else {
        this.$refs.pieDialog.showDialog(info, total, title, type)
      }
    },
    // 放大折线图
    showLineDialog () {
      this.$refs.lineDialog.showDialog(this.lineData)
    },
    // 放大柱状图
    showBarDialog () {
      this.$refs.barDialog.showDialog(this.barData)
    },
    // 根据时分获取日期时间
    getDateTime (shift) {
      let startArr = shift.startTime.split(':')
      let startDateTime = moment(date.buildDate({ hours: Number(startArr[0]), minutes: Number(startArr[1]), seconds: 0 }))
      shift.isStartTimeOnNextDay && startDateTime.add(1, 'd')

      let endArr = shift.endTime.split(':')
      let endDateTime = moment(date.buildDate({ hours: Number(endArr[0]), minutes: Number(endArr[1]), seconds: 0 }))
      shift.isEndTimeOnNextDay && endDateTime.add(1, 'd')

      if (shift.isYesterday) {
        startDateTime.subtract(1, 'd')
        endDateTime.subtract(1, 'd')
      }
      if (shift.isStartTimeOnNextDay) {
        startDateTime.subtract(1, 'd')
        endDateTime.subtract(1, 'd')
      }
      const params = {
        start: startDateTime.format('YYYY-MM-DDTHH:mm:ss'),
        end: endDateTime.format('YYYY-MM-DDTHH:mm:ss')
      }
      return params
    },
    // 获取最大值
    getMax (arr) {
      if (arr.length === 0) {
        return 0
      }
      let valArr = arr.map(item => item.value)
      return Math.max.apply(null, valArr)
    },
    goNotFillDetail () {
      if (!this.notWriteShow) return
      let today = moment().format('YYYY-MM-DD')
      if (moment().diff(moment(today + 'T' + this.shifts.startTime)) < 0) {
        today = moment().add(-1, 'days')
      }
      const startDate = moment(today).format('YYYY-MM-DDT') + this.shifts.startTime
      const endDate = this.shifts.isEndTimeOnNextDay ? moment(today).add(1, 'days').format('YYYY-MM-DDT') + this.shifts.endTime : moment(today).format('YYYY-MM-DDT') + this.shifts.endTime
      const params = {
        schemeId: (this.selTree.line && this.selTree.line.id) ? this.selTree.line.id : this.selTree.plant.id,
        schemeLevel: (this.selTree.line && this.selTree.line.id) ? '3' : '2',
        since: startDate,
        end: endDate
      }
      this.$router.push({
        path: '/main/status-monitor-v3/statistics/stop-reporting',
        query: {
          workshopId: this.selTree.plant.id,
          schemeId: params.schemeId,
          schemeLevel: params.schemeLevel,
          since: startDate,
          end: params.end,
          workshopName: this.selTree.plant.label
        }
      })
    }
  },
  components: {
    Box,
    Pie,
    realtimeJob,
    CurStatus,
    CurStatusDialog,
    SelPlantDialog,
    PieDialog,
    LineDialog,
    BarDialog,
    Drawer,
    Legend
  }
}
</script>

<style scoped lang="stylus">
  .content-container{
    margin-right -24px
    padding-right 24px
  }
  .right-container{
    width calc(100% / 3 * 2)
    padding-right 10px
    .row{
      margin 0 -10px
      .item{
        padding-left 10px
        padding-right 10px
        .chart-container{
          height 304px
          width 100%
        }
      }
    }
  }
  .left-container{
    width calc(100% / 3)
    padding-left 10px
    .list-container{
      border-radius 6px
      background-color #fff
      height 100%
      width 100%
      padding 20px
    }
  }
  .round{
    display inline-block
    vertical-align middle
    width 14px
    height 14px
    line-height 14px
    border-radius 7px
    margin-right 10px
  }

  .rank-table{
    $td-h = 48px
    tbody tr{
      &:first-child, &:nth-child(2), &:nth-child(3){
        background-color #fff
        &:hover{
          background-color #cfd6fe
        }
      }
      &:first-child td, &:nth-child(2) td, &:nth-child(3) td{
        position sticky
        z-index 1
      }
    }
  }

  @media (max-width $breakpoint-md-max){
    .img-h {
      height $td-md-height - 10
      margin-top 5px
    }
    .rank-index{
      width 25px
    }
    .rank-table tbody tr{
      &:first-child td{
        top $td-md-height
      }
      &:nth-child(2) td{
        top $td-md-height * 2 + 2
      }
      &:nth-child(3) td{
        top $td-md-height * 3 + 4
      }
    }
  }
  @media (min-width $breakpoint-lg-min) and (max-width $breakpoint-lg-max){
    .img-h {
      height $td-lg-height - 14
      margin-top 7px
    }
    .rank-index{
      width 25px
    }
    .rank-table tbody tr{
      &:first-child td{
        top $td-lg-height
      }
      &:nth-child(2) td{
        top $td-lg-height * 2
      }
      &:nth-child(3) td{
        top $td-lg-height * 3
      }
    }
  }
  @media (min-width $breakpoint-xl-min){
    .img-h {
      height $td-xl-height - 16
      margin-top 8px
    }
    .rank-index{
      width 27px
    }
    .rank-table tbody tr{
      &:first-child td{
        top $td-xl-height
      }
      &:nth-child(2) td{
        top $td-xl-height * 2
      }
      &:nth-child(3) td{
        top $td-xl-height * 3
      }
    }
  }
  .not-fill-detail{
    position absolute;
    right 60px;
    top 20px;
    color $primary;
    cursor pointer;
    user-select none;
  }
  .disable-detail{
    color #999999
    cursor not-allowed
  }
</style>
